package cn.aj.org.service.impl;

import cn.aj.basic.service.impl.BaseServiceImpl;
import cn.aj.basic.utils.MD5Utils;
import cn.aj.basic.utils.StrUtils;
import cn.aj.org.domain.Employee;
import cn.aj.org.mapper.EmployeeMapper;
import cn.aj.org.service.EmployeeService;
import cn.aj.system.mapper.RoleMapper;
import cn.aj.user.domain.Logininfo;
import cn.aj.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RoleMapper roleMapper;

    /**
    * @Title: add
    * @Description: TODO
    * @Author: Mr.GT
    * @Version: 1.0
    * @Date:  2022/12/1 0001 0:16
    * @Parameters: [employee]
    * @Return void
     * 员工新增角色
    */
    @Override
    public void add(Employee employee) {
        // 随机生成
        String randomString = StrUtils.getComplexRandomString(32);
        // 盐值
        String md5 = MD5Utils.encrypByMd5(randomString + 1);
        // 设置员工密码
        employee.setPassword(md5);
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee, logininfo); // emp转logininfo
        logininfo.setType(0);
        logininfo.setDisable(1);
        logininfoMapper.add(logininfo); // 先添加logininfo
        employee.setLogininfoId(logininfo.getId()); // 赋值logininfoid
        super.add(employee); // 最后添加员工
        // 添加角色,必须先添加员工,因为要先拿到员工的id才能保存中间表最后在保存角色表
        roleMapper.addEmpRole(employee.getId(), employee.getRoles());
    }

    /**
    * @Title: update
    * @Description: TODO
    * @Author: Mr.GT
    * @Version: 1.0
    * @Date:  2022/12/1 0001 0:16
    * @Parameters: [employee]
    * @Return void
     * 修改
    */
    @Override
    public void update(Employee employee) {
        super.update(employee);
        // 再新增
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee, logininfo); // emp转logininfo
        logininfo.setType(0);
        logininfo.setDisable(1);
        logininfoMapper.update(logininfo); // 先添加logininfo
        employee.setLogininfoId(logininfo.getId()); // 赋值logininfoid

        // 先删除中间表的员工id
        roleMapper.delEmpRole(employee.getId());
        // 添加角色,必须先添加员工,因为要先拿到员工的id才能保存中间表最后在保存角色表
        roleMapper.addEmpRole(employee.getId(), employee.getRoles());
    }
}
